﻿using Lanbt.Core.Cache;
using Lanbt.Core.Entity;
using Lanbt.Core.Entity.Dto;
using Lanbt.Core.Entity.Dto.lanbt_user;
using Lanbt.Core.Utility;
using Lanbt.Core.Utility.Extent;
using Lanbt.Core.Utility.Helper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;

namespace Lanbt.Core.Web.Filter
{
    /// <summary>
    /// 拦截器 验证用户token信息
    /// </summary>
    public class UserAuthorizeAttribute:Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            try
            {
                //判断是否过滤权限认证
                if (context.Filters.Any(q => q is CustomAllowAnonymousAttribute))
                {
                    context.HttpContext.User = new CurrentUser();
                    return;
                }

                var token = context.HttpContext.Request.Headers["Authorization"].ToString();
                if (token.IsNotNullOrEmpty())
                {
                    token = token.ReplaceByEmpty("Bearer").ReplaceByEmpty("bearer").Trim();
                    //验证Token 并解析Toke
                    var user = JwtHelper.VerificationToken(token);
                    if (user.IsError)
                    {
                        ResultOutput result = new ResultOutput()
                        {
                            Code = 401,
                            ErrorMsg = user.ErrorMsg,
                        };
                        context.Result = new ContentResult()
                        {
                            StatusCode = StatusCodes.Status401Unauthorized,
                            Content = JsonConvert.SerializeObject(result)
                        };
                        return;
                    }
                    context.HttpContext.User = user;

                    var currentUser = CacheFactory.Cache.GetCache<GetCurrentUserOutput>(string.Format(CacheKeys.login_userid, user.Id));

                    if (currentUser.IsNotNull())
                    {
                        if (!currentUser.IsAdmin)
                        {
                            string controllerName = context.ActionDescriptor.RouteValues["controller"].ToString().ToLower();//控制器名称
                            string actionName = context.ActionDescriptor.RouteValues["action"].ToString().ToLower();//方法名称
                            string path = controllerName + ":" + actionName;//控制器:方法
                            if (currentUser.PowerList.Count > 0 && !currentUser.PowerList.Any(q => q.ToLower().Contains(path)))//验证是否有该权限
                            {
                                ResultOutput result = new ResultOutput()
                                {
                                    Code = 402,
                                    ErrorMsg = $"您没有【{path}】权限，请联系管理员",
                                };
                                context.Result = new ContentResult()
                                {
                                    StatusCode = StatusCodes.Status402PaymentRequired,
                                    Content = JsonConvert.SerializeObject(result)
                                };
                            }
                        }
                    }

                }
                else
                {
                    ResultOutput result = new ResultOutput()
                    {
                        Code = 401,
                        ErrorMsg = "请先登录",
                    };
                    context.Result = new ContentResult()
                    {
                        StatusCode = StatusCodes.Status401Unauthorized,
                        Content = JsonConvert.SerializeObject(result)
                    };
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}
